
#include "EventDispatch.h"


EventDispatch::EventDispatch()
    : isDispatching_(false){
}

EventDispatch::~EventDispatch()
{
    this->Clear();
}


void EventDispatch::DispatchEvent(const std::string& name)
{
    EventBase* event = new EventBase();
    this->DispatchEvent(name, nullptr, event);
    delete event;
}

void EventDispatch::DispatchEvent(const std::string& name, Obj* info)
{
    EventBase* event = new EventBase();
    this->DispatchEvent(name, nullptr, event);
    delete event;
}

void EventDispatch::DispatchEvent(const std::string& name, Obj* info, EventBase* event)
{
    static std::vector<EventListener*> removeList;

    event->dispatcher_ = this;
    event->name_ = name;
    event->info_ = info;
    this->isDispatching_ = true;

    for(auto& it : this->listenerList_)
    {
        if(it->IsValid())
            it->ProcessEvent(name, event);
        if(!it->IsValid())
            removeList.push_back(it);
    }

    for(auto& it : removeList)
        this->RemoveListener(it);

    this->isDispatching_ = false;
}

void EventDispatch::AddListener(EventListener* listener)
{
    if(listener)
    {
        this->listenerList_.push_back(listener);
    }
}

void EventDispatch::RemoveListener(EventListener* listener)
{
    if(listener)
    {
        auto it = std::find(this->listenerList_.begin(), this->listenerList_.end(), listener);
        if(it != this->listenerList_.end())
            this->listenerList_.erase(it);
    }
}

void EventDispatch::Clear()
{
    while(!this->listenerList_.empty())
    {
        auto it = this->listenerList_.begin();
        (*it)->DisConnect();
    }
}

bool EventDispatch::IsDispatching() const
{
    return this->isDispatching_;
}
